//
//  HWOneYuanTradeController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/6/17.
//  Copyright © 2022 94hwan. All rights reserved.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift
import JXPagingView
class HWOneYuanTradeController: HWBaseViewController {
    
    var topBgImageView:UIImageView!
    var lineView:UIView!
    var titleButton:UIButton!
    var downArrow:UIImageView!
    
    var searchBgView:UIView!
    var searchField:UITextField!
    var searchLogoImageView:UIImageView!
    
    var tableView:UITableView!
    var tableViewProtocol = HWAccountTradeProtocol()
    
    var allButton:UIButton!
    var oneTagButton:UIButton!
    var twoTagButton:UIButton!
    var ThreeButton:UIButton!
    
    var textTagCollectionView:TTGTextTagCollectionView!
    let biaoqian = ["全部","0~50元","51~100元","100元以上"]
    let smoneyArr = ["","0","50","100"]
    let emoneyArr = ["","50","100","999999"]
    var selectIndex = 0
    var httpManager = HWOneYuanHttpManager()
    
    var sort = "0"
    var smoney = ""
    var emoney = ""
    var keyword = ""
    var system = ""
    var modelArr = NSMutableArray()
    
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addRefresh()
        
        addAction()
        
    }

}

extension HWOneYuanTradeController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        
        view.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
        
        topBgImageView = UIImageView()
        topBgImageView.image = UIImage(named: "oneyuan")
        view.addSubview(topBgImageView)
        
        lineView = UIView()
        lineView.backgroundColor = .colorWithHexString(hexString: "#333333")
        lineView.layer.cornerRadius = 2*widthScale
        view.addSubview(lineView)
        
        titleButton = UIButton(type: .custom)
        titleButton.setTitle("最新发布", for: .normal)
        titleButton.setTitleColor(.colorWithHexString(hexString: "#333333"), for: .normal)
        titleButton.titleLabel?.font = .systemFont(ofSize: 16*widthScale, weight: .medium)
        view.addSubview(titleButton)
        
        downArrow = UIImageView()
        downArrow.image = UIImage(named: "downArrow")
        view.addSubview(downArrow)
        
        searchBgView = UIView()
        searchBgView.frame = CGRect(x: 0, y: 0, width: 223*widthScale, height: 25*widthScale)
        searchBgView.backgroundColor = .white
        searchBgView.layer.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#C4C4C4", alpha: 0.16).cgColor
        searchBgView.layer.shadowOffset = CGSize(width: 0, height: 0)
        searchBgView.layer.shadowRadius = 6*widthScale
        searchBgView.layer.shadowOpacity = 1
        searchBgView.layer.cornerRadius = 12.5*widthScale
        searchBgView.layer.borderWidth = 1
        searchBgView.layer.borderColor = UIColor.colorWithHexString(hexString: "#EEEEEE").cgColor
        view.addSubview(searchBgView)
        
        searchLogoImageView = UIImageView()
        searchLogoImageView.image = UIImage(named: "search");
        searchBgView.addSubview(searchLogoImageView)
        
        searchField = UITextField()
        searchField.font = UIFont.systemFont(ofSize: 13*widthScale)
        searchField.delegate = self
        searchField.returnKeyType = .search
        searchField.textColor = .colorWithHexString(hexString: "#333333")
        searchBgView.addSubview(searchField)
        
        let placeHoldLabel = UILabel.init()
        placeHoldLabel.text = "搜索游戏查找商品"
        placeHoldLabel.textColor = UIColor.colorWithHexString(hexString: "#888888")
        placeHoldLabel.font = UIFont.systemFont(ofSize: 13*widthScale)
        searchField.setValue(placeHoldLabel, forKey: "_placeholderLabel")
        searchField.addTarget(self, action: #selector(searchTextFieldChange(_:)), for: .editingChanged)
        
        let innerShadow = CALayer()
        innerShadow.frame = searchBgView.bounds
        
        let path = UIBezierPath(rect: innerShadow.bounds.insetBy(dx: -1,dy: -1))
        let cutout = UIBezierPath(rect: innerShadow.bounds).reversing()
        path.append(cutout)
        innerShadow.shadowPath = path.cgPath
        innerShadow.masksToBounds = true
        
        innerShadow.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#989898", alpha: 0.5).cgColor
        innerShadow.shadowOffset = CGSize(width: 0,height: 0)
        innerShadow.shadowOpacity = 1
        innerShadow.shadowRadius = 4*widthScale
        innerShadow.cornerRadius = innerShadow.frame.size.height/2
        searchBgView.layer.addSublayer(innerShadow)
        
        textTagCollectionView = TTGTextTagCollectionView.init(frame: .zero)
        textTagCollectionView.alignment = TTGTagCollectionAlignment.left
        textTagCollectionView.numberOfLines = 1
        textTagCollectionView.manualCalculateHeight = true;
        textTagCollectionView.showsHorizontalScrollIndicator = false
        textTagCollectionView.scrollDirection = .horizontal
        textTagCollectionView.backgroundColor = .clear
        textTagCollectionView.delegate = self
        view.addSubview(textTagCollectionView)
        
        tableViewProtocol.isOneYuan = true
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
        
        
        for (idx,txt) in biaoqian.enumerated() {
            let content = TTGTextTagStringContent.init(text: txt)
            content.textColor = .colorWithHexString(hexString: "#333333")
            content.textFont = UIFont.systemFont(ofSize: 14*widthScale)
            
            let selectContent = TTGTextTagStringContent.init(text: txt)
            selectContent.textColor = .white
            selectContent.textFont = UIFont.systemFont(ofSize: 14*widthScale)
            
            let normalStyle = TTGTextTagStyle.init()
            normalStyle.cornerRadius = 4*widthScale
            normalStyle.extraSpace = CGSize.init(width: 22*widthScale, height: 13*widthScale)
            normalStyle.backgroundColor = .white
            normalStyle.shadowColor = .white
            normalStyle.borderColor = .white
            normalStyle.shadowOffset = CGSize (width: 0, height: 0)
            normalStyle.shadowRadius = 0
            normalStyle.shadowOpacity = 0
            normalStyle.borderWidth = 1
            
            let selectStyle = TTGTextTagStyle.init()
            selectStyle.cornerRadius = 4*widthScale
            selectStyle.extraSpace = CGSize.init(width: 22*widthScale, height: 13*widthScale)
            selectStyle.backgroundColor = .colorWithHexString(hexString: "#FA8C08")
            selectStyle.shadowColor = .colorWithHexString(hexString: "#FA8C08")
            selectStyle.borderColor = .colorWithHexString(hexString: "#FA8C08")
            selectStyle.borderWidth = 1
            
            let tag = TTGTextTag.init()
            tag.content = content
            tag.style = normalStyle
            tag.selectedContent = selectContent
            tag.selectedStyle = selectStyle
            
            if idx == 0 {
                tag.selected = true
            }
            textTagCollectionView.addTag(tag)
        }
    }
    
    private func initFrame() -> Void {
        
        topBgImageView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(158*widthScale)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18*widthScale).priority(.high)
            make.top.equalTo(topBgImageView.snp.bottom).offset(23*widthScale)
            make.height.equalTo(18*widthScale)
            make.width.equalTo(4*widthScale)
        }
        
        titleButton.snp.makeConstraints { make in
            make.centerY.equalTo(lineView)
            make.left.equalTo(lineView.snp.right).offset(5*widthScale)
        }
        
        downArrow.snp.makeConstraints { make in
            make.left.equalTo(titleButton.snp.right).offset(7*widthScale)
            make.width.height.equalTo(14*widthScale)
            make.centerY.equalTo(titleButton)
        }
        
        searchBgView.snp.makeConstraints { make in
            make.left.equalTo(downArrow.snp.right).offset(23*widthScale)
            make.centerY.equalTo(lineView)
            make.height.equalTo(25*widthScale)
            make.right.equalTo(-15*widthScale)
        }
        
        searchLogoImageView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(9*widthScale)
            make.width.height.equalTo(14*widthScale)
        }
        
        searchField.snp.makeConstraints { make in
            make.left.equalTo(searchLogoImageView.snp.right).offset(6*widthScale)
            make.height.equalTo(18*widthScale)
            make.centerY.equalToSuperview()
            make.right.equalTo(-10*widthScale)
        }
        
        textTagCollectionView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.left.equalTo(18*widthScale)
            make.top.equalTo(lineView.snp.bottom).offset(9*widthScale)
        }
        
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(textTagCollectionView.snp.bottom).offset(9*widthScale)
        }
        
        titleButton.setContentHuggingPriority(.required, for: .horizontal)
    }
}
extension HWOneYuanTradeController:JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return self.tableView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
}

//extension HWOneYuanTradeController:JXSegmentedListContainerViewListDelegate {
//    func listView() -> UIView {
//        return view
//    }
//}
extension HWOneYuanTradeController:TTGTextTagCollectionViewDelegate{
    func textTagCollectionView(_ textTagCollectionView: TTGTextTagCollectionView!, didTap tag: TTGTextTag!, at index: UInt) {
        self.selectIndex = Int(index)
        for i in 0..<biaoqian.count {
            textTagCollectionView.updateTag(at: UInt(i), selected: false)
        }
        smoney = smoneyArr[Int(index)]
        emoney = emoneyArr[Int(index)]
        self.loadData()
        textTagCollectionView.updateTag(at: UInt(self.selectIndex), selected: true)
    }
}

extension HWOneYuanTradeController {
    func loadData() -> Void {
        tableView.mj_footer?.isHidden = true
        
        httpManager.getAccountDetailTradeList(sort: sort, system: system, smoney: smoney, emoney: emoney, keyword: keyword,huishouzhanghao:"1") { models in
            self.modelArr.removeAllObjects()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.tableView.mj_footer?.isHidden = false
                self.modelArr.removeAllObjects()
                self.modelArr.addObjects(from: models)
            }
            self.tableViewProtocol.models = self.modelArr as? [HWGameDetailTradeModel]
            self.tableView.reloadData()
        } failure: { errorString in
            self.modelArr.removeAllObjects()
            self.tableViewProtocol.models = self.modelArr as? [HWGameDetailTradeModel]
            self.tableView.reloadData()
            self.tableView.mj_footer?.isHidden = true
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
    
    
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        tableView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.tableView.mj_footer?.endRefreshing()
        httpManager.getAccountDetailTradeListFooter(sort: sort, system: system, smoney: smoney, emoney: emoney, keyword: keyword,huishouzhanghao:"1") { models in
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.addObjects(from: models)
            }
            self.tableViewProtocol.models = self.modelArr as? [HWGameDetailTradeModel]
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}

extension HWOneYuanTradeController {
    func addAction() -> Void {
        self.tableViewProtocol.didClickItem = {
            model in
            let detail = HWAccountDetailsViewController()
            detail.idStr = model.id
//            detail.isOneYuan = true
            self.navigationController?.pushViewController(detail, animated: true)
        }
        
        tableViewProtocol.scrollDidScroll = {
            scrollView in
            self.listViewDidScrollCallback?(scrollView)
        }
    }
}
extension HWOneYuanTradeController:UITextFieldDelegate {
    @objc func searchTextFieldChange(_ textField:UITextField) ->Void {
        if textField.text?.count == 0 {
            keyword = ""
            loadData()
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.endEditing(true)
        keyword = textField.text ?? ""
        loadData()
        return true
    }
}
